//
//  JrdTabCommonController.m
//  iMandarin
//
//  Created by dhcui on 16/7/22.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdTabCommonController.h"
#import "JrdCommon.h"
#import "MJRefreshGifHeader.h"
#import "JRDCourseCell.h"
#import "MJRefreshAutoNormalFooter.h"
#import "JrdCourseDetailViewController.h"
#import "CKHttpCommunicate.h"
#import "JZCateModel.h"
@interface JrdTabCommonController ()<UITableViewDataSource, UITableViewDelegate>{
    NSMutableArray *courseLastest;

    NSInteger _page;/**< 页数 */
    NSInteger _limit;/**< 每页的个数 */
    NSInteger _charge;/**< 1：免费；2：收费 */
}
@property (nonatomic, strong) UITableView* tableView;

@end

@implementation JrdTabCommonController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor  = JrdBackgroundColor;
    [self initData];
}

- (void)loadView{
    [super loadView];
    [self configureTable];
}
- (void)initData{
    _page = 1;
    _limit = 20;
    _charge = 1;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)configureTable{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT )
                                                                  style:UITableViewStylePlain];
    //self.tableView.style = UITableViewStylePlain;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator=NO;

    [self setupTableview];
}

- (void)loadNewData{
    _page = 1;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseData];
    });
}

- (void)loadMoreData{
    _page++;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseData];
    });
    
}

-(void)setupTableview{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; ++i) {
        UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [idleImages addObject:image];
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    //设置即将刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
    [refreshingImages addObject:image1];
    UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
    [refreshingImages addObject:image2];
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    //马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}

#pragma mark - UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return courseLastest.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return JRD_COURSE_TABLE_H;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndentifier = @"courseCell2";
    NSMutableArray* value = nil;//courseLastest[indexPath.row];
    
    JRDCourseCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[JRDCourseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        //            NSLog(@"%f/%f",cell.frame.size.width,cell.frame.size.height);
        //下划线
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 71.5, SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = JRD_RGB(200, 199, 204);
        [cell addSubview:lineView];
    }
    JrdCourseModel *jrdCourseM = [[JrdCourseModel alloc] init];
    
            jrdCourseM.courseName = [courseLastest[indexPath.row] objectForKey:@"CourseName"];
            jrdCourseM.courseDes = [NSString stringWithFormat:@"%@课时",[courseLastest[indexPath.row] objectForKey:@"ClassNumber"]];
            jrdCourseM.coursePhoto = [courseLastest[indexPath.row] objectForKey:@"PhotoURL"];
    [cell setJzCourseM:jrdCourseM];
    
    return cell;
}


#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    NSMutableArray* value = nil;
    //Go to course detail view controller
        value = courseLastest[indexPath.row];
    JrdCourseModel* jrdCoursmodel = [[JrdCourseModel alloc] init];
    jrdCoursmodel.courseName = [value valueForKey:@"CourseName"];
    jrdCoursmodel.courseDes =[value valueForKey:@"description"];
    jrdCoursmodel.coursePhoto = [value valueForKey:@"PhotoURL"];
    jrdCoursmodel.courseChapter = [value valueForKey:@"ClassNumber"];
    jrdCoursmodel.SID = [value valueForKey:@"SID"];
    jrdCoursmodel.courseId = [value valueForKey:@"CourseID"];
    JrdCourseDetailViewController* vc = [[JrdCourseDetailViewController alloc] init];
    vc.coursemodel = jrdCoursmodel;
    [self.navigationController pushViewController:vc animated:YES];
    
}


#pragma mark - fake data
- (void)getCourseData{
    NSDictionary *parameter;
        parameter = @{@"mod":@"search",
                      @"act":@"mobile",
                      @"from":@"iPhone",
                      @"page":[NSString stringWithFormat:@"%ld",_page],
                      @"limit":[NSString stringWithFormat:@"%ld",_limit],
                      @"today":@"1",
                      @"charge":[NSString stringWithFormat:@"%ld",_charge],
                      };
    
    __weak typeof(self) weakself = self;
    [CKHttpCommunicate createRequest:HTTP_IMANDARIN_NULL WithParam:parameter withMethod:GET success:^(id result) {
        if (result) {
            NSMutableArray *ClassListArray = [result objectForKey:@"ClassList"];
                    if(nil == courseLastest){
                        courseLastest = [[NSMutableArray alloc] init];
                    }
                    
                    if(1 == _page){
                        [courseLastest removeAllObjects];
                    }
                    for (int i = 0; i < ClassListArray.count; i++) {
                        JZCateModel *jzCateM = [ClassListArray objectAtIndex:i];
                        [courseLastest addObject:jzCateM];
                    }
            NSLog(@"result:%@",result);
        }
        [weakself.tableView reloadData];
        [weakself.tableView.mj_header endRefreshing];
        [weakself.tableView.mj_footer endRefreshing];
    } failure:^(NSError *erro) {
        
    } showHUD:nil];
    
}


@end
